package message.test.service;

import lodsve.mybatis.datasource.annotations.DataSourceProvider;
import lodsve.mybatis.key.IDGenerator;
import message.test.domain.Demo;
import message.test.domain.enums.Sex;
import message.test.repository.DemoDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * .
 *
 * @author sunhao(sunhao.java @ gmail.com)
 * @version V1.0, 15/6/26 上午10:37
 */
@Service
public class DemoService {
    @Autowired
    private DemoDAO demoDAO;
    @Autowired
    private IDGenerator idGenerator;

    @DataSourceProvider("demo")
    public Demo selectFromDemo(Long id) {
        return demoDAO.load(id);
    }

    @DataSourceProvider("test")
    public Demo selectFromTest(Long id) {
        return demoDAO.load(id);
    }

    @DataSourceProvider("test")
    public int insertIntoTest(Demo t) {
        t.setPkId(idGenerator.nextId("demo_sequence"));
        return demoDAO.save(t);
    }

    @DataSourceProvider("demo")
    public int insertIntoDemo(Demo t) {
        return demoDAO.save(t);
    }

    @DataSourceProvider("demo")
    public Page<Demo> listFromDemo(Pageable pageable) {
        return demoDAO.list(pageable);
    }

    @DataSourceProvider("test")
    public Page<Demo> listFromTest(Pageable pageable) {
        return demoDAO.list(pageable);
    }

    @DataSourceProvider("demo")
    @Transactional
    public void demoTransactional() {
        for (int i = 0; i < 10; i++) {
            Demo demo = new Demo(Long.valueOf(i + ""), "demo_" + i, Sex.FEMALE);
            if (i == 4) {
                throw new RuntimeException("test insert demo error!");
            }
            demoDAO.save(demo);
        }
    }

    @DataSourceProvider("test")
    @Transactional
    public void testTransactional() {
        for (int i = 0; i < 10; i++) {
            Demo demo = new Demo(Long.valueOf(i + ""), "test_" + i, Sex.MALE);
            if (i == 4) {
                throw new RuntimeException("test insert test error!");
            }
            demoDAO.save(demo);
        }
    }
}
